// @ts-nocheck
import React, { FC, useState, useEffect, useMemo } from "react";
import {
  NavBar,
  Button,
  Form,
  Input,
  Cascader,
  TextArea,
  ImageUploader,
  Toast,
} from "antd-mobile";
import { Spin } from "antd";
import { useNavigate } from "react-router-dom";
import { CascaderOption } from "antd-mobile/es/components/cascader";
import { getListToOptions } from "@/utils/tools";
import { IAddressItem } from "@/components/MapComponent";
// service
import {
  getTypes,
  IEventList,
  putEventReportByFromData,
  upLoadImage,
} from "./service";
import { getCurrentUser } from "@/utils/authority";
import { HandOk } from "@/components";

// style
import "./index.less";

interface IFormState {
  title: string;
  type: string[];
  address: string;
  addressDetailedUser: string;
  content: string;
}

interface IStartFormState {
  questiontitle: string;
  eventType: string;
  hadress: string; //位置
  desc: string; //描述
  longitude: number; //经度
  latitude: number; //纬度
  // discoveryTime: string;
  // eventNo: string; //事件编号
  // selfDisposal: "confirmDisposal" | "vetoDisposal";//是否自行处置
  fileFront: string[];
  // fileBack:string[];
}

function EventReport() {
  const userId = getCurrentUser()?.data?.user_id;
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);
  const [ImageList, setImageList] = useState<{ url: string; name: string }[]>([]);
  const [addressItem, setAddressItem] = useState<IAddressItem | {}>({});
  const [users, setUsers] = useState();
  const [loaing, setLoaing] = useState(false);
  const [handOk, setHandOk] = useState(false)
  const [eventList, setEventList] = useState<CascaderOption[]>([
    {
      label: "人居环境",
      value: "人居环境",
    },
    {
      label: "社区安全",
      value: "社区安全",
    },
    {
      label: "咨询建议",
      value: "咨询建议",
    },
    {
      label: "邻里关系",
      value: "邻里关系",
    },
    {
      label: "物业服务",
      value: "物业服务",
    },
  ]);

  const onFinish = async (values: IFormState) => {
    const attachList: string[] = ImageList.map((item) => {
      return item.url;
    });
    setLoaing(true);
    const formCommitData: IStartFormState = {
      questiontitle: values.title,
      eventType: values.eventType[values.eventType.length - 1],
      hadress: values.address,
      desc: values.content,
      longitude: addressItem.longitude,
      latitude: addressItem.latitude,
      fileFront: attachList,
    };
    try {
      const parma = formCommitData;
      const { success } = await putEventReportByFromData(parma);
      if (!success) {
        Toast.show({
          icon: "fail",
          content: "上报失败",
        });
        setLoaing(false);
        return;
      }
      if (success) {
        setLoaing(false);
        // Toast.show({
        //   icon: "success",
        //   content: "上报成功",
        // });
        setHandOk(true)
        // navigate("/");
      }
    } catch (err) {
      console.error(err);
    }
  };



  const handleMapOnFocous = () => {
    const formItem = form.getFieldsValue();
    localStorage.setItem("herf", "");
    // console.log(formItem, "formItem");
    localStorage.setItem("form", JSON.stringify(formItem));
    navigate(`/eventReport/location?local=eventReport`);
  };

  const getEventOptions = (x: IEventList) => {
    const obj: CascaderOption = {
      label: x.categoryCompleteName,
      value: x.categoryCompleteName,
    };
    if (x?.categoryChild) {
      obj["children"] = getListToOptions(x.categoryChild, getEventOptions);
    }
    return obj;
  };

  const getEventTypeList = async () => {
    try {
      const { data, code, msg } = await getTypes();
      if (code === 200) {
        const arr = data.map(item => {
          return {
            label: item,
            value: item
          }
        })
        setEventList(arr)
      }
    } catch (err) {
      console.error(err);
    }
  };

  async function mockUpload(file: File) {
    try {
      const { data } = await upLoadImage({ file: file });
      if (data?.code === 200) {
        Toast.show({
          icon: "success",
          content: "上传成功",
        });
        const url = data.data.length && data.data[0].link;
        const name = data.data.length && data.data[0].name;
        return {
          url,
          name,
        };
      } else {
        Toast.show({
          icon: "fail",
          content: "上传失败",
        });
        return {
          url: "",
        };
      }
    } catch (err) {
      Toast.show({
        icon: "fail",
        content: "上传失败",
      });
      return {
        url: "",
      };
    }
  }

  useEffect(() => {
    const formItem = JSON.parse(
      localStorage.getItem("form") || JSON.stringify("")
    );
    form.setFieldsValue(formItem);
    const addressItems = JSON.parse(
      localStorage.getItem("address") || JSON.stringify({})
    );
    const users = JSON.parse(
      localStorage.getItem("users") || JSON.stringify({})
    );
    setUsers(users);
    setAddressItem(addressItems);
    getEventTypeList();
    return () => {
      localStorage.removeItem("form");
      localStorage.removeItem("address");
      form.resetFields();
    };
  }, []);

  const Basic = useMemo(() => {
    return (
      <div>
        <div className="figImg">多添加图片，能更清晰的表明事件地点</div>
        <ImageUploader
          maxCount={3}
          showUpload={ImageList.length < 3}
          value={ImageList}
          onChange={setImageList}
          upload={mockUpload}
          multiple={false}
          // maxCount={0}
          capture={true}
          accept ={'.jpg,.png,.jpeg'}
        />
      </div>
    );
  }, [ImageList]);

  return (
    handOk ? <HandOk topTitle="受理成功" title="请等待社区开通" header='事件上报' />
      :
      <Spin tip="提交中..." spinning={loaing}>
        <div className="reportcontent">
          <div>
            <NavBar
              onBack={() => navigate(-1)}
            >
              <div className="commontitle">事件上报</div>
            </NavBar>
          </div>

          <div className="eventFrom">
            <Form form={form} onFinish={onFinish}>
              <Form.Item
                name="eventType"
                label="事件类型"
                trigger="onConfirm"
                onClick={() => {
                  setVisible(true);
                }}
                rules={[{ required: true, message: "必填项" }]}
              >
                <Cascader
                  options={eventList}
                  visible={visible}
                  onClose={() => {
                    setVisible(false);
                  }}
                >
                  {(items) => {
                    if (items.every((item) => item === null)) {
                      return <div className="colour">点击选择事件类型</div>;
                    } else {
                      return items[items.length - 1]?.label;
                    }
                  }}
                </Cascader>
              </Form.Item>
              <Form.Item
                name="title"
                label="事件标题"
                rules={[{ required: true, message: "必填项" }]}
              >
                <Input placeholder="请输入事件标题" />
              </Form.Item>
              {/* <Form.Item name="addressDetailedUser" label="详细地址">
              <Input placeholder="请输入详细地址" />
            </Form.Item> */}
              <Form.Item
                name="content"
                label="事件描述"
                className="eventContent"
                rules={[{ required: true, message: "必填项" }]}
              >
                <TextArea placeholder="请输入事件描述" rows={4} />
              </Form.Item>
              <Form.Item
                name="address"
                label="事件发生位置"
                rules={[{ required: true, message: "必填项" }]}
              >
                <Input placeholder="请输入事件发生位置" onFocus={() => { handleMapOnFocous() }} />
              </Form.Item>
              <Form.Item
                label="事件照片"
                rules={[{ required: true, message: "必填项" }]}
                className="BasicBox"
              >
                {Basic}
              </Form.Item>
              <div className="bottomButton">
                <Button
                  onClick={(e) => {
                    if (!loaing) {
                      e.preventDefault();
                      form.submit();
                    }
                  }}
                  type="submit"
                  className="reportbtn "
                  style={{ fontSize: "1.5rem" }}
                >
                  {loaing ? "提交中" : "提交"}
                </Button>
              </div>
            </Form>

          </div>
        </div>
      </Spin>
  );
}

export default EventReport;
